﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestNetty.Service.Model;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace TestNetty.Service.Handlers
{
    /// <summary>
    /// 解码器（将JSON格式的ByteBuf转换为消息对象）：
    /// </summary>
    public class JsonDecoder : ByteToMessageDecoder
    {
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
        {
            try
            {
                if (input.IsReadable())
                {
                    int readableBytes = input.ReadableBytes;//缓冲区获取到byte数组
                    byte[] bytes = new byte[readableBytes];//获取到的放入容器中
                    input.ReadBytes(bytes);// 读取所有可读字节到bytes数组中
                    string json = Encoding.UTF8.GetString(bytes);// 将字节转换为字符串  
                    

                    var message = JsonConvert.DeserializeObject<MyMessage>(json);// 反序列化JSON为MyMessage对象
                    if (message != null )
                    {
                    output.Add(message);// 将反序列化后的对象添加到输出列表中
                }
                    else
                    {
                        //记录日志
                    }

                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
